import { Component, OnInit } from '@angular/core';
import { ModalController, NavParams } from '@ionic/angular';
import { pb } from 'src/pb';
import { CallService } from '../call.service';

@Component({
  selector: 'app-select-path',
  templateUrl: './select-path.page.html',
  styleUrls: ['./select-path.page.scss'],
})
export class SelectPathPage implements OnInit {

  file = '';
  folder: pb.IFolder = {};
  private setting: pb.IFolderSettings = { path: '' };
  private path = '';
  constructor(
    private navParams: NavParams,
    private modalCtrl: ModalController,
    private callService: CallService,
  ) {
    this.path = this.navParams.get('path');
  }

  async ngOnInit() {
    this.setting = await this.callService.call('get', { def: this.setting }, 'folder');
    if (this.path) {
      await this.load(this.path);
      return;
    }

    if (!this.setting) {
      this.setting = { path: '' };
    }

    await this.load(this.setting.path);
  }

  select(f: pb.IFileInfo) {
    if (f.isDir) {
      this.load(this.folder.path, f.name);
      return;
    }

    this.modalCtrl.dismiss(`${this.folder.path}/${f.name}`);
  }

  up() {
    this.load(this.folder.path, '..');
  }

  close() {
    this.modalCtrl.dismiss();
  }

  private async load(...paths: string[]) {
    this.folder = await this.callService.call('folder', {
      msg: '目录加载', def: {
        path: '/home/ender',
        files: [
          { name: 'work', isDir: true, modTime: 33 },
          { name: 'a.txt', isDir: false, size: 333, modTime: 333 },
          { name: 'b.txt', isDir: false, size: 4444444, modTime: 333 },
        ],
      }
    }, paths);

    this.setting.path = this.folder.path;
    await this.callService.call('set', { def: this.setting }, 'folder', this.setting);
  }
}
